<template>
  <info-page-container @goListPage="cancel">
    <div class="info-data-container full-container flex-column">
      <div class="farmer-container flex-column">
        <div class="farmer-info-container">
          <user-info @changeFarmer="changeFarmer" :farmer-info="farmerInfo"></user-info>
        </div>
        <div class="chit-info-container">
          <el-form :rules="rules" :model="dataForm" ref="baseForm" size="small"
                   label-width="80px">
            <el-form-item class="column-item" label="投保金额" prop="money">
              <el-input
                type="number"
                v-model="dataForm.money"
                placeholder="请输入投保金额"
                clearable
              >
              </el-input>
            </el-form-item>
            <div class="flex-row form-item-parent">
              <el-form-item class="column-item half-item" label="保险生效时间" prop="startTime">
                <el-date-picker
                  v-model="dataForm.startTime"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
              <el-form-item class="column-item half-item" label="保险失效时间" prop="endTime">
                <el-date-picker
                  v-model="dataForm.endTime"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </div>

          </el-form>
        </div>
      </div>

      <div class="list-container">
        <layout-container title="地块列表">
          <template slot="title">
            <div class="important-txt">
              总面积：{{ sumArea }} 亩
            </div>
          </template>
          <template>
            <el-table
              class="diy-table"
              ref="plotTable"
              @selection-change="handlePlotSelectionChange"
              :data="plotList"
              style="width: 100%;" height="100%">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                prop="plotNo"
                label="编号">
              </el-table-column>
              <el-table-column
                prop="geometryArea"
                label="面积（亩）">
              </el-table-column>

              <el-table-column width="150" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="locationByData(plotLayerId,scope.row,'地块信息')"
                  >定位
                  </el-button>
                </template>
              </el-table-column>

            </el-table>
          </template>
        </layout-container>
      </div>

      <div class="handle-bt-container flex-row">
        <el-button class="diy-bt" icon="el-icon-refresh" size="mini" @click="save">保存</el-button>
        <el-button class="diy-bt" icon="el-icon-refresh" size="mini" @click="cancel">取消</el-button>
      </div>

    </div>

    <el-dialog :close-on-click-modal="false" title="选择农户" :visible.sync="openFlag" width="700px" append-to-body>
      <div class="dia-log-container">
        <div class="query-form-container flex-row">
          <div class="form-container">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
                     label-width="68px">
              <el-form-item label="" prop="projectName">
                <el-input
                  v-model="queryParams.farmerName"
                  placeholder="请输入农户名称"
                  clearable
                  @keyup.enter.native="getListData"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="" prop="">
                <el-button class="diy-bt" size="mini" @click="getListData">查 询</el-button>
              </el-form-item>
              <el-form-item label="" prop="">
                <el-button class="diy-bt" size="mini" @click="resetQuery">重 置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="list-page-content">
          <el-table
            v-if="openFlag"
            @select="handleSelectionChange"
            class="diy-table"
            :data="listData"
            ref="farmerTable"
            style="width: 100%;" height="100%">
            <el-table-column
              :selectable="selectable"
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="farmerNo"
              label="农户编号">
            </el-table-column>
            <el-table-column
              prop="farmerName"
              label="农户名称">
            </el-table-column>
            <el-table-column
              prop="farmerAge"
              label="年龄">
            </el-table-column>
            <el-table-column
              prop="farmerSex"
              label="性别">
              <template slot-scope="scope">
                {{ scope.row.farmerSex == SEX_CONFIG.MAN ? '男' : '女' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="diy-bt" @click="setCurrentFarmer(HANDLE_TYPE.CHECK_ALL_PLOTS)">确 认</el-button>
        <el-button class="diy-bt" @click="openFlag = false">关 闭</el-button>
      </div>
    </el-dialog>
  </info-page-container>
</template>

<script>
import {infoPageMixins} from "@/views/business/mixins/infoPageMixins";
import {pageBaseMapMixins} from "@/views/business/mixins/pageBaseMapMixins";
import {GEOMETRY_TYPE, HANDLE_TYPE, REFRESH_PAGE_TYPE, SEX_CONFIG} from "@/views/business/constantData";
import ListPageContainer from "@/components/ListPageContainer/index.vue";
import {listPageMixins} from "@/views/business/mixins/listPageMixins";
import {addFarmer, getAllPlot, getFarmerInfo, getFarmerList, updateFarmer} from "@/api/business/userManagement";
import {isArr} from "@/utils/arrayUtil";
import {GET_LOCATE_SYMBOL} from "@/utils/SymbolUtils";
import userInfo from "@/views/business/components/UserInfo/index.vue";

export default {
  mixins: [listPageMixins, infoPageMixins, pageBaseMapMixins],
  components: {
    ListPageContainer,
    userInfo
  },
  data() {
    const HANDLE_TYPE = {
      CHECK_ALL_PLOTS: 'checkAllPlots',
      NO_CHECK: 'noCheck'
    }
    return {
      HANDLE_TYPE,
      plotList: [],
      queryParams: {
        farmerName: ''
      },
      openFlag: false,
      currentTableFarmer: null,
      farmerInfo: null,
      currentFarmerPlotList: [],
      plotLayerId: 'plot',
      farmerPlotId: 'farmerPlotId',
      chitLayerId: 'chit',
      dataForm: {
        money: null,
        startTime: null,
        endTime: null,
      },
      rules: {
        money: [
          {required: true, message: '投保金额不能为空', trigger: 'blur'},
        ],
        startTime: [
          {required: true, message: '保险生效时间不能为空', trigger: 'change'},
        ],
        endTime: [
          {required: true, message: '保险失效时间不能为空', trigger: 'change'},
        ],
      },
      disabledFarmerIdList:[],
      SEX_CONFIG,
      baseFarmerId:''
    }
  },
  computed: {
    sumArea() {
      let {currentFarmerPlotList} = this
      return isArr(currentFarmerPlotList) ? _.round(_.sum(_.map(currentFarmerPlotList, item => item.geometryArea)), 2) : 0
    },
  },
  methods: {
    async changeFarmer() {
      let {farmerInfo} = this
      this.startLoading()
      let currentCheckFarmerList = await this.getGraphicByGeometryAndWhere({layerId: this.chitLayerId});
      if (!isArr(currentCheckFarmerList)) {
        this.disabledFarmerIdList = []
        this.openFlag = true
        this.endLoading()
        return
      }
      this.disabledFarmerIdList = [...new Set(currentCheckFarmerList.map(item => item.attributes.farmerId))]
      if (farmerInfo) {
        this.disabledFarmerIdList = this.disabledFarmerIdList.filter(id => id != farmerInfo.id);
        let owner = this
        this.$nextTick(() => {
          owner.$nextTick(() => {
            owner.$refs.farmerTable.toggleRowSelection(owner.listData.find(item => item.id == farmerInfo.id));
          })
        })
      }
      this.openFlag = true
      this.endLoading()
    },
    selectable(row, index) {
      return !this.disabledFarmerIdList.some(id => id == row.id)
    },
    async setCurrentItem(currentItem) {
      if (!currentItem) {
      } else {
        this.baseFarmerId = currentItem.farmerId
        this.clearBuffer()
        this.currentTableFarmer = this.listData.find(item => item.id == currentItem.farmerId)
        await this.setCurrentFarmer()
        this.dataForm = {
          money: currentItem.money,
          startTime: currentItem.startTime,
          endTime: currentItem.endTime,
        }
        this.plotList.forEach(row => {
          if (currentItem.plotIds.some(id => id == row.id)) {
            this.$refs.plotTable.toggleRowSelection(row);
          }
        })
      }
    },
    clearBuffer() {
      this.plotList = []
      this.currentFarmerPlotList = []
      this.farmerInfo = null
      this.dataForm = {
        money: null,
        startTime: null,
        endTime: null,
      }
    },
    async setCurrentFarmer(handelType) {
      let owner = this
      return new Promise((resolve, reject) => {
        let {currentTableFarmer} = owner
        if (!currentTableFarmer && handelType == owner.HANDLE_TYPE.CHECK_ALL_PLOTS) {
          owner.$message({
            message: '请选择农户',
            type: 'error'
          })
          resolve()
          return
        }
        owner.farmerInfo = _.cloneDeep(currentTableFarmer)
        this.startLoading()
        getFarmerInfo(currentTableFarmer).then(async res => {
          owner.plotList = res.data.farmerPlots
          if (handelType == owner.HANDLE_TYPE.CHECK_ALL_PLOTS) {
            owner.$nextTick(() => {
              res.data.farmerPlots.forEach(row => {
                owner.$refs.plotTable.toggleRowSelection(row);
              })
            })
          }
        }).finally(() => {
          owner.openFlag = false
          owner.endLoading()
          resolve()
        });
      })

    },
    handlePlotSelectionChange(val) {
      this.currentFarmerPlotList = _.cloneDeep(val)
      this.heightCurrentFarmerPlot()
    },
    heightCurrentFarmerPlot: _.throttle(async function () {
      this.removeFarmerLayer()
      let owner = this
      let {currentFarmerPlotList} = this
      return new Promise(async (resolve, reject) => {
        if (!isArr(currentFarmerPlotList)) {
          resolve()
          return
        }
        let where = ''
        currentFarmerPlotList.forEach((item, index) => {
          where = index != 0 ? `${where} or id = '${item.id}'` : `id = '${item.id}'`
        })
        let currentFarmerFeatures = await owner.getGraphicByGeometryAndWhere({layerId: owner.farmerPlotId, where});
        if (isArr(currentFarmerFeatures)) {
          await this.addFarmerLayer(currentFarmerFeatures)
        }
        resolve()
      })
    }, 200),
    async addFarmerLayer(source) {
      let owner = this;
      this.setAreaToFeatures(source);
      return new Promise(async (resolve, reject) => {
        const geometryType = GEOMETRY_TYPE.POLYGON;
        const txtFileList = [
          {
            value: 'farmerName',
            label: '农户名称',
          },
          {
            value: 'plotNo',
            label: '地块编号',
          },
          {
            value: this.areaFiled,
            label: '面积',
            suffix: ' 亩'
          },
        ]

        if (owner.currentHandleType == HANDLE_TYPE.UPDATE) {
          txtFileList.unshift({
            value: 'plotNo',
            label: '地块编号',
          })
          txtFileList.unshift({
            value: 'farmerName',
            label: '农户名称',
          })
        }
        await owner.addLayer({
          layerId: owner.plotLayerId,
          source,
          rendererSymbol: GET_LOCATE_SYMBOL(geometryType),
          geometryType,
          txtFileList,
          txtColor: '#000',
          fontSize: 15
        })
        resolve()
      })
    },
    handleSelectionChange(val, currentRow) {
      this.$refs.farmerTable.clearSelection();
      this.$refs.farmerTable.toggleRowSelection(currentRow);
      this.currentTableFarmer = _.cloneDeep(currentRow)
    },
    cancel() {
      this.clearBuffer()
      this.removeFarmerLayer()
      this.goListPage(REFRESH_PAGE_TYPE.REFRESH)
    },
    saveFinish() {
      this.removeFarmerLayer()
      let {
        sumArea,
        currentFarmerPlotList,
        farmerInfo: {farmerName, farmerNo, id: farmerId, farmerIdentity},
        dataForm: {money, startTime, endTime}
      } = this
      let plotIds = currentFarmerPlotList.map(item => item.id)
      let removeFarmerId = this.baseFarmerId == farmerId ? '' : this.baseFarmerId
      this.clearBuffer()
      this.$emit('saveFinish', {farmerChit:{
          plotIds,
          farmerName,
          farmerIdentity,
          farmerNo,
          farmerId,
          money,
          startTime,
          endTime,
          sumArea
        },removeFarmerId})
    },
    removeFarmerLayer() {
      this.removeRender()
      this.removeLayer({layerId: this.plotLayerId})
    },
    save() {
      let owner = this
      this.$refs.baseForm.validate((valid) => {
        if (valid) {
          let {currentFarmerPlotList} = this
          if (!isArr(currentFarmerPlotList)) {
            this.$message({
              message: '请选择要投保的地块',
              type: 'error'
            })
            return
          }
          owner.saveFinish()
        }
      });
    },
    locationByData(layerId, row, popupTitle) {
      let {id} = row
      const where = `id = '${id}'`
      this.locationByWhere({layerId, where, openPopupFlag: true, popupTitle})
    },
    async getListData() {
      this.removeFarmerLayer()
      let farmerRes = await getFarmerList(this.queryParams)
      this.listData = farmerRes.rows
    },
  },
};
</script>

<style scoped lang="scss">
.info-data-container {
  .farmer-container {
    height: 35%;
    max-height: 35%;

    .farmer-info-container {
      width: 100%;
      height: 40%;
    }

    .chit-info-container {
      width: 100%;
      height: 60%;
    }
  }

  .list-container {
    height: 55% !important;
  }


}

.dia-log-container {
  height: 350px;
  width: 100%;

  .query-form-container {
    height: 50px;
  }

  .list-page-content {
    height: 300px;

    ::v-deep .el-table {
      .el-table__header-wrapper {
        .el-table__header {
          .el-table-column--selection {
            visibility: hidden;
          }
        }
      }
    }
  }
}
</style>
